import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Col, Row, Table, message, Spin } from 'antd';
import queryString from 'query-string';
import moment from 'moment';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;
@connect(({ serviceconfig, loading }) => ({
  serviceconfig,
  loading: loading.models.serviceconfig,
  configDetailData: serviceconfig.configDetailData,
}))
@Form.create()
class AdvancedForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      cityList: [],
      payWayList: [], // 产品缴费方式
      kindsList: [], // 险种
      areaDataSource: [],
    };
    this.formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 14 },
    };
  }

  componentDidMount() {
    const { location, dispatch } = this.props;
    const currentObj = queryString.parse(location.search);
    // 获取所有的市
    dispatch({
      type: 'serviceconfig/getNmAreaCity',
      payload: {},
    }).then(response => {
      if (response.success) {
        this.setState({ cityList: response.data });
      } else {
        message.warning(`${response.message || '暂无数据！'}`);
      }
    });
    // 获取页面所需字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['BIZ_ACCU_TYPE', 'BIZ_INS_TYPE', 'PAY_FEES_WAY'],
    }).then(data => {
      const sortNumber = (a, b) => a.itemCode - b.itemCode;
      const arr = [
        {
          itemCode: '1',
          itemName: '社保',
        },
      ];
      this.setState({
        payWayList: data.PAY_FEES_WAY.sort(sortNumber),
        kindsList: data.BIZ_ACCU_TYPE.concat(data.BIZ_INS_TYPE).concat(arr),
      });
    });
    // 获取详情数据
    dispatch({
      type: 'serviceconfig/getConfigDetail',
      payload: {
        custConfId: currentObj.custConfId,
      },
    }).then(response => {
      if (response.data) {
        if (response.data.confDetList && response.data.confDetList.length) {
          // 生成地区配置的数据
          const confDetListRes = response.data.confDetList;
          const areaDataSource = [];
          const { cityList } = this.state;
          let areaNum = 0;
          confDetListRes.forEach(item => {
            const existedAreaData = areaDataSource.filter(
              areaData => areaData.areaId === item.areaId
            );
            if (existedAreaData.length === 0) {
              // 如果以前没有这个地区配置新增地区配置
              const newData = {
                id: areaNum,
                key: areaNum,
                cityList,
                areaId: item.areaId,
                insUnifyFlag: item.insSetFlag,
                confDetList: [
                  {
                    custConfDetId: item.custConfDetId,
                    id: areaNum,
                    key: 0,
                    kind: item.kind,
                    payWay: item.payWay,
                    payAcco: item.payName,
                    accoName: item.accoName,
                  },
                ],
              };
              // eslint-disable-next-line no-plusplus
              areaNum++;
              areaDataSource.push(newData);
            } else {
              areaDataSource.forEach(areaData => {
                if (areaData.areaId === item.areaId) {
                  // 如果以前有这个地区新增一行
                  areaData.confDetList.push({
                    custConfDetId: item.custConfDetId,
                    id: areaData.id,
                    key: areaData.confDetList.length,
                    kind: item.kind,
                    payWay: item.payWay,
                    payAcco: item.payName,
                    accoName: item.accoName,
                  });
                }
              });
            }
          });
          this.setState({ areaDataSource });
        }
      }
    });
  }

  // 渲染函数
  render() {
    const { loading, configDetailData } = this.props;
    const { areaDataSource, cityList, kindsList, payWayList } = this.state;
    const columns = [
      {
        title: '险种',
        dataIndex: 'kind',
        key: 'kind',
        width: 200,
        render: text =>
          kindsList.map(item => (
            <span>{Number(item.itemCode) === text ? item.itemName : null}</span>
          )),
      },
      {
        title: '缴费方式',
        dataIndex: 'payWay',
        key: 'payWay',
        width: 200,
        render: text =>
          payWayList.map(item => (
            <span>{Number(item.itemCode) === text ? item.itemName : null}</span>
          )),
      },
      {
        title: '缴费账户',
        dataIndex: 'accoName',
        key: 'accoName',
        width: 200,
        render: text => (text && text) || '--',
      },
      {
        title: '政策组合',
        dataIndex: 'payAcco',
        key: 'payAcco',
        width: 200,
        render: text => (text && text) || '--',
      },
    ];

    return (
      <Form layout="horizontal">
        <PageHeaderWrapper wrapperClassName={styles.advancedForm}>
          <Spin tip="Loading..." spinning={loading}>
            <Card className={styles.searchCard}>
              <Row>
                <Col span={8}>
                  <FormItem label="客户名称" {...this.formItemLayout}>
                    {(configDetailData.custName &&
                      configDetailData.suppName &&
                      `${configDetailData.custName}(${configDetailData.suppName})`) ||
                      `${configDetailData.custName || '--'}`}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="配置名称" {...this.formItemLayout}>
                    {configDetailData.custConfName || '--'}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="配置编号" {...this.formItemLayout}>
                    {configDetailData.custConfNo || '--'}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={8}>
                  <FormItem label="备注" {...this.formItemLayout}>
                    {configDetailData.remark || '--'}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={8}>
                  <FormItem label="所属客服" {...this.formItemLayout}>
                    {configDetailData.primName || '--'}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="创建时间" {...this.formItemLayout}>
                    {moment(configDetailData.creTime).format('YYYY-MM-DD HH:mm') || '--'}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="创建人" {...this.formItemLayout}>
                    {configDetailData.creName || '--'}
                  </FormItem>
                </Col>
              </Row>
            </Card>
            {areaDataSource.length > 0 ? (
              <Row>
                {areaDataSource.map(item =>
                  cityList.map(city =>
                    city.areaId === item.areaId ? (
                      <Card key={item.custConfDetId} title={city.areaName} style={{ width: '100%' }}>
                        <Table
                          pagination={false}
                          dataSource={item.confDetList}
                          rowKey="custConfDetId"
                          columns={columns}
                        />
                      </Card>
                    ) : null
                  )
                )}
              </Row>
            ) : null}
          </Spin>
          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={() => router.goBack()}>返回</Button>
          </FooterToolbar>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default AdvancedForm;
